package org.opens.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.opens.mybatisplus.dao.FormatDao;
import org.opens.mybatisplus.pojo.FormatPojo;
import org.opens.mybatisplus.service.FormatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service(value = "formatService")
public class FormatServiceImpl implements FormatService {

    @Autowired
    private FormatDao formatDao;

    @Override
    public FormatPojo selectOneByIdAndName(int id, String name) {
        if(id < 1) {
            return null;
        }
        if(StringUtils.isEmpty(name)) {
            return null;
        }
        QueryWrapper<FormatPojo> wrapper = new QueryWrapper<>();
        //这么一长串是因为lombok默认转换为的是驼峰命名, 但是在mybaits要求的字段是数据库中的字段, 所以需要将属性的名称变为数据库中字段的名称, 如果使用jpa则不用, 这个优化同样可以使用到jpa中.
        wrapper.eq(StringUtils.camelToUnderline(FormatPojo.Fields.id), id);
        wrapper.eq(StringUtils.camelToUnderline(FormatPojo.Fields.name), name);
        return formatDao.selectOne(wrapper);
    }

    @Override
    public List<FormatPojo> findByStratDate(String startDateStr) {
        LocalDate date = LocalDate.parse(startDateStr, DateTimeFormatter.ISO_LOCAL_DATE);
        LocalTime initTime = LocalTime.of(1, 0, 0);
        LocalDateTime dateTime = LocalDateTime.of(date, initTime);
        return formatDao.findByStartTime(dateTime);
    }
}
